package com.beerandjesus.sportofkings.handicapper.profile.resolver;

import com.beerandjesus.sportofkings.handicapper.model.brisnet.singlefile.Horse;
import com.beerandjesus.sportofkings.handicapper.model.brisnet.singlefile.HorseRace;
import com.beerandjesus.sportofkings.handicapper.model.brisnet.singlefile.PastPerformance;
import com.beerandjesus.sportofkings.handicapper.profile.Profile;
import com.beerandjesus.sportofkings.handicapper.profile.ProfileType;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;

import static com.beerandjesus.sportofkings.handicapper.profile.ProfileBuilder.analysisProfile;

/**
 * Attempts to identify runners who are consistently in the money (i.e.,
 * about 70% of the time or more).
 */
@Component
public class InTheMoneyProfileResolver implements ProfileResolver {

    public static final BigDecimal SEVENTY_PERCENT = new BigDecimal(.70d);
    public static final BigDecimal ONE_HUNDRED = new BigDecimal(100);
    public static final BigDecimal MINUS_ONE_HUNDRED = new BigDecimal(-100);

    public Profile resolve(HorseRace race, Horse horse) {
        List<PastPerformance> pps = horse.getPastPerformances();
        int total = pps.size();
        if (total < 4) {
            return null;
        }
        int inTheMoneyCount = 0;
        // Discount runners who meet the profile but have not been in the money
        // in the most recent starts
        int notInTheMoney = 0;
        int ppCount = 0;
        for (PastPerformance pp : pps) {
            ppCount++;
            try {
                int pos = Integer.parseInt(pp.getFinishPosition());
                if (pos <= 3) {
                    inTheMoneyCount++;
                    if (ppCount <= 3) {
                        notInTheMoney = 0;
                    }
                } else {
                    notInTheMoney++;
                }
            } catch (NumberFormatException e) {
                // Ignore
            }
        }
        BigDecimal value = new BigDecimal(inTheMoneyCount).divide(new BigDecimal(total), 2, RoundingMode.HALF_DOWN);
        if (value.compareTo(SEVENTY_PERCENT) >= 0) {
            int score;
            if (notInTheMoney >= 3) {
                score = value.multiply(MINUS_ONE_HUNDRED).intValue();
            } else {
                score = value.multiply(ONE_HUNDRED).intValue();
            }
            return analysisProfile(ProfileType.ALWAYS_IN_THE_MONEY, score);
        }
        return null;
    }
}
